package com.situ.mall.web.controller;

import com.situ.mall.common.entity.Member;
import com.situ.mall.common.exception.MyException;
import com.situ.mall.common.service.IMemberService;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.util.SendSMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;


@Controller
@RequestMapping("/register")
public class RegisterController {


    @Autowired
    private IMemberService memberService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @GetMapping("/page")
    public String page() {
        return "register";
    }

    //接受一个手机号 发短信
    @PostMapping("/sendCode")
    @ResponseBody
    public String sendCode(String tel) {
        //验证之前这个手机有没有注册过
        Member m = memberService.selectByTel(tel);
        if (m != null) {
           throw new MyException("手机号已注册");
        }
        //使用发短信工具发短信
        int i = (int) (Math.random() * 900000 + 100000);
        //把生成的验证码存在redis中，5分钟内有效
        redisTemplate.opsForValue().set("r-" + tel, i, 5, TimeUnit.MINUTES);
        //参数 模板号 手机号 内容
        //阿里云拷贝一份发短信的工具类
        SendSMSUtil.sendMessage("SMS_463661132", tel, String.valueOf(i));
        return String.valueOf(i);


    }


    //成功注册 就会进这
    @PostMapping("/registerSuccess")
    public String registerSuccess(String tel, String code, String password1) {
        //先判断code对不对
        Object o = redisTemplate.opsForValue().get("r-" + tel);
        Integer code1 = Integer.valueOf(code);
        if (o == null || !o.equals(code1)) {
            throw new MyException("验证码错误");
        } else {
            //派memberService去注册这个账号
            Member m = new Member();
            m.setUsername(tel);
            m.setTel(tel);
            m.setPassword(password1);
            memberService.save(m);
        }
        return "login";
    }
}
